<?php

namespace backend\widgets;


use backend\assets\BatchViewAsset;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\base\Widget;
use yii\helpers\Html;
use Yii;
use yii\helpers\Json;
use yii\helpers\Url;

class BatchView extends Widget
{
    public $checkboxName = 'id';

    public $options = ['class' => 'form-inline batch-view'];

    public $batchUrl;

    public $batchSelector;

    public $grid;

    public $columns = [];

    public $model;

    public function init()
    {
        parent::init();

        if (!isset($this->options['id'])) {
            $this->options['id'] = $this->getId();
        }

        if (!isset($this->grid)) {
            throw new InvalidConfigException('grid 不能为空');
        }

        if (!$this->grid instanceof GridView) {
            throw new InvalidConfigException('grid 必须是 ' . GridView::className() . ' 的实例');
        }

        if (isset($this->model) && !$this->model instanceof Model) {
            throw new InvalidConfigException('model 必须是 ' . Model::className() . ' 的实例');
        }


        if (substr_compare($this->checkboxName, '[]', -2, 2)) {
            $this->checkboxName .= '[]';
        }

        echo Html::beginTag('div', $this->options);
    }

    public function run()
    {
        $id = $this->options['id'];
        $view = $this->getView();
        BatchViewAsset::register($view);
        $options = Json::encode($this->getClientOptions());
        $view->registerJs("jQuery('#$id').ycmfBatchView($options);");
        echo $this->renderColumns();
        echo Html::endTag('div');
    }

    public function renderColumns()
    {
        $output = '';
        foreach ($this->columns as $column) {
            $column['batch'] = $this;
            $output .= BatchColumn::widget($column);
        }
        return $output;
    }

    /**
     * Returns the options for the grid view JS widget.
     * @return array the options
     */
    protected function getClientOptions()
    {
        $id = $this->options['id'];
        $batchUrl = isset($this->batchUrl) ? $this->batchUrl : Yii::$app->request->url;
        $batchSelector = "#$id input, #$id select, #$id button";
        if (isset($this->batchSelector)) {
            $batchSelector .= ', ' . $this->batchSelector;
        }

        return [
            'batchUrl' => Url::to($batchUrl),
            'batchSelector' => $batchSelector,
            'gridId' => $this->grid->options['id'],
            'checkboxName' => $this->checkboxName,
        ];
    }
}